var dateUtils = require('../../../utils/dateUtil.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    countPic: 9, //上传图片最大数量
    imgDetailPics: [], //作业页面显示的图片
    showImgUrl: "", //路径拼接，一般上传返回的都是文件名，
    theacherImgDetailPics: [], //老师发布作业的图片
    uploadImgUrl: '', //图片的上传的路径

    // switchList:[
    //   // {title:'已提交',dataList:[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]},
    //   // {title:'未提交',dataList:[{},{},{},{},{},{},{},{},{},{},{}]},
    // ],
    switchList: [{
        title: '已提交',
        dataList: [{}, {}, {}]
      },
      {
        title: '未提交',
        dataList: [{}, {}, {}]
      }
    ],
    selectIndex: 0, //0 已提交 1未提交
    // needLine:true,
    // isShowDetail:true,
    modal: null,
    taskId: '',
    taskInfo: {},
    commitInfo: {},
    unCommittedStu: {}, //已提交未点评学生
    //unCommittedStuName: [], //已提交未点评学生姓名
    // dateString: "", //选中的日期
    spot: [], //日期红点集合
    taskEndTime: '', //任务结束日期
    defaultTime: '',
  },

  dateChange(e) {
    //var tempDta = dateUtils.formatTime(new Date());
    // this.setData({
    //   dateString: e.detail.dateString
    // })
    if (this.data.taskId) {
      var mBooleTime = false
      for (var i = 0; i < this.data.spot.length; i++) {
        //console.log("选中日期变了,现在日期是2=", this.data.spot[i].substr(0, 10))
        if (this.data.spot[i].substr(0, 10) == e.detail.dateString) {
          mBooleTime = true
          break;
        }
      }
      if (mBooleTime) {
        if (dateUtils.compareTime(dateUtils.formatTime(new Date()), e.detail.dateString)) {
          wx.showToast({
            title: '该打卡日还未到',
            icon: 'none',
          })
          this.selectComponent("#calendarbg").selectReturnChange(this.data.defaultTime)
        } else {

          //tempDta = e.detail.dateString
          this.queryTeacherSkipRopeDayDetail(e.detail.dateString)
        }
      } else {
        wx.showToast({
          title: '当日无打卡任务',
          icon: 'none',
        })
        //this.selectComponent("#calendarbg").selectReturnChange(this.data.dateString)
      }
    }
    console.log("选中日期变了,现在日期是", e.detail.dateString + "  " + this.data.defaultTime)

  },


  delTask() { //解除
    this.selectComponent("#modal").showModal({
      title: '确认删除',
      modalType: 0,
      placeholderText: '请输入',
      content: '是否删除本条任务记录？\n（注：删除后家长端同步删除此任务）',
      topImageUrl: '../../static/new/alert_deleted.png',
      complete: (res) => {

        if (res.cancel) {

        }

        if (res.confirm) {
          this.delTaskInfo()
        }
      }
    })
  },

  //批量点评
  goAllComment() {
    if (!this.data.commitInfo.committed || this.data.commitInfo.committed.length <= 0) {
      wx.showToast({
        title: '暂无学生提交任务',
        icon: 'none',
      })
      return
    }

    if(!this.data.unCommittedStu || this.data.unCommittedStu.length<=0){
      wx.showToast({
        title: '暂无点评的学生',
        icon: 'none',
      })
      return
    }

    this.modal.showModal({
      content: '选择学生',
      modalType: 4,
      contentMoreList: this.data.unCommittedStu,
      complete: (res) => {
        if (res.cancel) {

        }
        if (res.confirm) {
          console.log("批量==="+JSON.stringify(res.data.chooseContentMoreList));
          if(res.data.chooseContentMoreList == null || res.data.chooseContentMoreList.length<=0){
            wx.showToast({
              title: '请选择点评学生',
              icon: 'none',
            })
          }else{
            this.goplComment(JSON.stringify(res.data.chooseContentMoreList))
          }
          
        }
      }
    })
  },




  //查询任务当日打卡详情
  queryTeacherSkipRopeDayDetail(finishTime) {
    this.setData({
      commitInfo: {},
      switchList: [{
          title: '已提交',
          dataList: [{}, {}, {}]
        },
        {
          title: '未提交',
          dataList: [{}, {}, {}]
        }
      ],
      unCommittedStu: {},
      //unCommittedStuName: [],
      defaultTime: finishTime
    })


    var data = {
      taskId: this.data.taskId,
      finishTime: finishTime,
    }
    console.log("查询任务当日打卡详情参数=" + JSON.stringify(data));
    wx.showLoading({
      title: '数据加载中...',
      icon: 'none',
    })
    var that = this;
    app.api.queryTeacherSkipRopeDayDetail(data).then(rest => {
        wx.hideLoading()
        this.setData({
          isLoading: false
        })
        if (rest && rest.success) {
          console.log('查询任务当日打卡详情列表数据2=' + JSON.stringify(rest))
          var swList = that.data.switchList
          var commitNum = Object.keys(rest.data.committed).length > 0 ? rest.data.committed.length : 0
          swList[0].title = "已提交" + "(" + commitNum + ")"
          swList[1].title = "未提交" + "(" + rest.data.unCommitted.length + ")"

          var unCommittedStu = [];
          //var unCommittedStuName = [];
          for (var i = 0; i < rest.data.committed.length; i++) {

            if (rest.data.committed[i].status == 2) {
              unCommittedStu.push(rest.data.committed[i])
              // let dt = rest.data.committed[i]
              // dt.name = dt.studentName
              
              // unCommittedStuName.push(dt)

            }
          }

          that.setData({
            commitInfo: rest.data,
            switchList: swList,
            unCommittedStu: unCommittedStu,
            //unCommittedStuName: unCommittedStuName
          })
          console.log('未点评学生列表=' + JSON.stringify(unCommittedStu))
        } else {
          wx.showToast({
            title: rest.errMsg || '网络异常,请重试！',
            icon: 'none',
            duration: 2000,
            mask: true
          })
        }
      })
      .catch(r => {
        console.error(r)
        wx.showToast({
          title: '网络异常,请重试！',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      })
  },


  //删除任务
  delTaskInfo() {
    wx.showLoading({
      title: '任务删除中...',
      icon: 'none',
    })
    app.api.delTask(this.data.taskId).then(rest => {
        wx.hideLoading()
        console.log('接口数据a=' + JSON.stringify(rest));
        if (rest && rest.success) {
          wx.showToast({
            title: '任务删除成功',
            success: function () {

              let pages = getCurrentPages(); //当前页面
              let prevPage = pages[pages.length - 2]; //上一页面
              prevPage.setData({ //直接给上移页面赋值
                isRefresh: 1

              });

              wx.navigateBack({
                delta: 1, // 返回上一级页面。
                success: function () {}
              })
            },
            icon: 'none',
            duration: 1500,
            mask: true
          })

        } else {
          console.log('接口数据==' + rest.errMsg)
          wx.showToast({
            title: rest.errMsg || '网络异常，请稍后重试！！',
            icon: 'none',
            duration: 2000,
            mask: true
          })
        }
      })
      .catch(r => {
        wx.hideLoading()
        console.error(r)
        wx.showToast({
          title: '网络异常，请稍后重试！',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      })
  },


  //查看点评
  seekComment(e) {
    wx.navigateTo({
      //url: '/packJumpTask/teacher/taskComment/taskComment', 
      url: '/packJumpTask/teacher/seeComment/seeComment?index=' + e.currentTarget.dataset.index + '&info=' + JSON.stringify(this.data.commitInfo.committed),
    })
  },
  //去点评
  goComment(e) {
    wx.navigateTo({
      //url: '/packJumpTask/teacher/taskComment/taskComment', 
      url: '/packJumpTask/teacher/taskComment/taskComment?type=0&taskId=' + this.data.taskId + '&info=' + JSON.stringify(this.data.commitInfo.committed[e.currentTarget.dataset.index]),
    })
  },

  //去批量点评
  goplComment(unCommittedStu) {
    wx.navigateTo({
      //url: '/packJumpTask/teacher/taskComment/taskComment', 
      url: '/packJumpTask/teacher/taskComment/taskComment?type=1&taskId=' + this.data.taskId + '&info=' + unCommittedStu,
    })
  },

  didClickIndex(e) {
    let index = e.detail;
    this.setData({
      selectIndex: index
    })
    console.log('打印：' + index)
  },

  //监听组件事件，返回的结果
  myEventListener: function (e) {
    console.log("上传的图片结果集合=" + e.detail.picsList)
    this.setData({
      imgDetailPics: e.detail.picsList
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(this.options.taskId + "===")
    var taskId = this.options.taskId;
    this.setData({
      taskId: taskId
    })
    this.getTaskInfo()
    //this.queryTeacherSkipRopeDayDetail(dateUtils.formatDataTime(new Date()));
  },

  //获取任务详情
  getTaskInfo() {
    wx.showLoading({
      title: '数据加载中...',
      icon: 'none',
    })
    app.api.TaskDetail(this.data.taskId).then(rest => {
        wx.hideLoading()

        if (rest && rest.success) {
          this.setData({
            taskInfo: rest.data,
            spot: rest.data.ruleTimes,
            taskEndTime: rest.data.ruleTimes[rest.data.ruleTimes.length - 1],
          })

          console.log(this.data.defaultTime + '==接口数据a=' + JSON.stringify(rest));
          var date = dateUtils.formatTime(new Date());
          var ifOk = false
          for (var i = 0; i < this.data.spot.length; i++) {
            if (date === this.data.spot[i]) {
              ifOk = true;
              break;
            }
          }
          console.log(ifOk + '==setDefaultTime接口数据比较=' + date);
          if (ifOk) {
            this.setData({
              defaultTime: date
            })
            //this.selectComponent("#calendarbg").setDefaultTime(date)
            this.queryTeacherSkipRopeDayDetail(date)
          } else {
            if (dateUtils.compareTime(date, this.data.taskEndTime)) {
              this.setData({
                defaultTime: date
              })
              //this.selectComponent("#calendarbg").setDefaultTime(date)
            } else {
              this.setData({
                defaultTime: this.data.taskEndTime
              })
              //this.selectComponent("#calendarbg").setDefaultTime(this.data.taskEndTime)
            }
          }
          this.selectComponent("#calendarbg").setDefaultTime(this.data.defaultTime)
        } else {
          console.log('接口数据==' + rest.errMsg)
          wx.showToast({
            title: rest.errMsg || '网络异常，请稍后重试！！',
            icon: 'none',
            duration: 2000,
            mask: true
          })
        }
      })
      .catch(r => {
        wx.hideLoading()
        console.error(r)
        wx.showToast({
          title: '网络异常，请稍后重试！',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.modal = this.selectComponent("#modal")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})